package com.matt.service.impl;

import com.dotflat.util.excelUtil.StringUtils;
import com.matt.domain.LiveRoom;
import com.matt.service.LiveAddressService;
import org.springframework.stereotype.Service;

import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 * *******************************
 * Created by Ron.
 * form com.matt
 * on 2017/8/1
 * *******************************
 */
@Service
public class LiveAddressServiceImpl implements LiveAddressService {

    private String SECRET_JK_3 = "";
    private String SECRET_JK_2 = "";
    private String SECRET_JK_1 = ""; //s1
    private String SECRET_BIZ_1 = "";

    private static String md5Sum(String src) {
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        md5.update(StandardCharsets.UTF_8.encode(src));
        return String.format("%032x", new BigInteger(1, md5.digest()));
    }

    private static String aAuth(String uri, String key, long exp) {
        String pattern = "^((rtmp://)|(http://)|(https://))?([^/?]+)(/[^?]*)?(\\\\?.*)?$";
        Pattern r = Pattern.compile(pattern);
        Matcher m = r.matcher(uri);
        String scheme = "", host = "", path = "", args = "";

        if (m.find()) {
            for (int i = 1; i < m.groupCount(); i++){
                System.out.println(m.group(i));
            }

            scheme = m.group(1) == null ? "rtmp://" : m.group(1);
            host = m.group(4) == null ? "" : m.group(4);
            path = m.group(5) == null ? "/" : m.group(5);
            args = m.group(6) == null ? "" : m.group(6);
        } else {
            System.out.println("NO MATCH");
        }

        String rand = "0";  // "0" by default, other value is ok
        String uid = "0";   // "0" by default, other value is ok
        String sString = String.format("%s-%s-%s-%s-%s", path, exp, rand, uid, key);
        String hashValue = md5Sum(sString);
        String authKey = String.format("%s-%s-%s-%s", exp, rand, uid, hashValue);
        if (args.isEmpty()) {
            return String.format("%s%s%s%s?auth_key=%s", scheme, host, path, args, authKey);
        } else {
            return String.format("%s%s%s%s&auth_key=%s", scheme, host, path, args, authKey);
        }
    }

//    public static void main(String[] args) {
//        String uri = "rtmp://example.aliyundoc.com/live/test****";  // original uri
//        String key = "<input private key>";                       // private key of authorization
//        long exp = System.currentTimeMillis() / 1000 + 1 * 3600;  // expiration time: 1 hour after current time
//        String authUri = aAuth(uri, key, exp);                    // auth type:
//        System.out.printf("URL : %s\nAuth: %s", uri, authUri);
//    }

    @Override
    public List generatePushAddress(String stage, String areaName, int count){
        return generatePushAddress(stage, areaName, "", count);
    }

    public List generatePushAddress(String stage, String areaName, String suffix, int count){
        String pushFormat = "rtmp://live.push.jk%s.xybaby365.com/s%s/%s_d%03d";
        String playFormat = "http://live.jk%s.xybaby365.com/s%s/%s_d%03d.m3u8";

        if (StringUtils.isNotEmpty(suffix)){
//            http://live.jk2.xybaby365.com/s2/mafangtou_d013_toh264.m3u8?auth_key=1819619860-0-0-9c99126e8a8dd77580b6b98967de816f&ext=.m3u8
            pushFormat = "rtmp://live.push.jk%s.xybaby365.com/s%s/%s_d%03d";
            playFormat = "http://live.jk%s.xybaby365.com/s%s/%s_d%03d_%s.m3u8";
        }

        long exp = System.currentTimeMillis() / 1000 + 365 * 24 * 3600;

        String key = null;
        if ("3".equals(stage)){
            key = SECRET_JK_3;
        }else if ("2".equals(stage)){
            key = SECRET_JK_2;
        }

        List result = new ArrayList();

        for (int i = 0; i < count ; i++){
            String push = null;
            String play = null;

            if (StringUtils.isNotEmpty(suffix)){
                push = String.format(pushFormat, stage, stage, areaName, i);
                play = String.format(playFormat, stage, stage, areaName, i, suffix);
             }else {
                push = String.format(pushFormat, stage, stage, areaName, i);
                play = String.format(playFormat, stage, stage, areaName, i);
            }

            push = aAuth(push, key, exp);
            play = aAuth(play, key, exp) + "&ext=.m3u8";

            result.add("===" + areaName + "===" + i);
            result.add(push);
            result.add(play);
        }

        return result;
    }

    public void getPlayUrl(  List<LiveRoom>  list) { 
        //30分钟有效
        long exp = System.currentTimeMillis() / 1000 + 1800;

        for (int i = 0; i <list.size(); i++) {
            LiveRoom o = list.get(i);
            String key = null;
            String url = String.valueOf(o.getUrl());
            if (null != url){
                if (url.indexOf("/s3/") >= 0 ) {
                    key = SECRET_JK_3;
                } else if (url.indexOf("/s2/") >= 0 ) {
                    key = SECRET_JK_2;
                } else if (url.indexOf("/s1/") >= 0 ) {
                    key = SECRET_JK_1;
                } else if (url.indexOf("/b1/") >= 0 ) {
                    key = SECRET_BIZ_1;
                }else{
                    continue;
                }
            }
            if (url.indexOf("?") >= 0 ){
                url =  url.substring(0,url.indexOf("?"));
            }
            String play = aAuth(url, key, exp) + "&ext=.m3u8";
            o.setUrl(play);
        }
    }
    @Override
    public List generateBizPushAddress(String stage, String areaName, int count){
        return generatePushAddress(stage, areaName, "", count);
    }

    public List generateBizPushAddress(String stage, String areaName, String suffix, int count){
//        live.push.biz1.xybaby365.com
//        live.biz1.xybaby365.com

        String pushFormat = "rtmp://live.push.biz%s.xybaby365.com/b%s/%s_d%03d";
        String playFormat = "http://live.biz%s.xybaby365.com/b%s/%s_d%03d.m3u8";
        if (StringUtils.isNotEmpty(suffix)){
//            http://live.jk2.xybaby365.com/s2/mafangtou_d013_toh264.m3u8?auth_key=1819619860-0-0-9c99126e8a8dd77580b6b98967de816f&ext=.m3u8
            pushFormat = "rtmp://live.push.biz%s.xybaby365.com/b%s/%s_d%03d";
            playFormat = "http://live.biz%s.xybaby365.com/b%s/%s_d%03d_%s.m3u8";
        }

        long exp = System.currentTimeMillis() / 1000 + 365 * 24 * 3600;

        String key = null;
        if ("1".equals(stage)){
            key = SECRET_BIZ_1;
        }

        List result = new ArrayList();

        for (int i = 0; i < count ; i++){
            String push = null;
            String play = null;

            if (StringUtils.isNotEmpty(suffix)){
                push = String.format(pushFormat, stage, stage, areaName, i);
                play = String.format(playFormat, stage, stage, areaName, i, suffix);
            }else {
                push = String.format(pushFormat, stage, stage, areaName, i);
                play = String.format(playFormat, stage, stage, areaName, i);
            }
//            String push = String.format(pushFormat, stage, stage, areaName, i);
//            String play = String.format(playFormat, stage, stage, areaName, i);

            push = aAuth(push, key, exp);
            play = aAuth(play, key, exp) + "&ext=.m3u8";

            result.add("===" + areaName + "===" + i);
            result.add(push);
            result.add(play);
        }

        return result;
    }
}
